<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="租户名" prop="name">
            <el-input v-model.trim="formData.name" placeholder="请输入租户名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否显示非业务菜单" prop="showNonBizMenu" label-width="auto">
            <el-radio-group v-model.trim="formData.showNonBizMenu">
              <el-radio :label="true"> 是</el-radio>
              <el-radio :label="false"> 否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="租户套餐" prop="packageId">
            <el-select v-model.trim="formData.packageId" clearable placeholder="请选择租户套餐">
              <el-option
                v-for="item in packageList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租户状态" prop="status">
            <el-radio-group v-model.trim="formData.status">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名称" prop="contactName">
            <el-input v-model.trim="formData.contactName" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系手机" prop="contactMobile">
            <el-input v-model.trim="formData.contactMobile" placeholder="请输入联系手机" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="用户账号" prop="username">
            <el-input v-model.trim="formData.username" placeholder="请输入用户账号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="用户密码" prop="password">
            <el-input
              v-model.trim="formData.password"
              placeholder="请输入用户密码"
              show-password
              type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="账号额度" prop="accountCount">
            <el-input-number
              v-model.trim="formData.accountCount"
              :min="0"
              controls-position="right"
              placeholder="请输入账号额度"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="过期时间" prop="expireTime">
            <el-date-picker
              v-model.trim="formData.expireTime"
              clearable
              placeholder="请选择过期时间"
              type="date"
              value-format="x"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <el-form-item label="绑定域名" prop="domain">-->
      <!--        <el-input v-model.trim="formData.domain" placeholder="请输入绑定域名" />-->
      <!--      </el-form-item>-->
      <el-form-item label="图片地址" prop="imgUrl">
        <el-input v-model.trim="formData.imgUrl" placeholder="请输入图片地址" />
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="c端账号" prop="csAccount">
            <el-input
              v-model.trim="formData.csAccount"
              placeholder="请输入c端账号"
              @blur="listPlatform()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="c端密码" prop="csPassword">
            <el-input
              v-model.trim="formData.csPassword"
              placeholder="请输入c端密码"
              show-password
              type="password"
              @blur="listPlatform()"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="体测平台" prop="csPlatformId">
            <el-select
              placeholder="请选择体测平台"
              clearable
              filterable
              v-model="formData.csPlatformId"
            >
              <el-option
                v-for="item in csPlatform"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考试平台" prop="csZkPlatformId">
            <el-select
              placeholder="请选择考试平台"
              clearable
              filterable
              v-model="formData.csZkPlatformId"
            >
              <el-option
                v-for="item in csZkPlatform"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="模块">
            <el-select v-model="formData.moduleIds" multiple placeholder="请选择模块">
              <el-option
                v-for="item in moduleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="展示额外模块" prop="showExtraModule" label-width="auto">
            <el-switch v-model.trim="formData.showExtraModule" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 列表 -->
    <ContentWrap v-if="formData.tenantAdminList">
      <el-table :data="formData.tenantAdminList">
        <el-table-column label="用户ID" prop="id" show-overflow-tooltip />
        <el-table-column label="用户账号" prop="username" show-overflow-tooltip />
        <el-table-column label="联系手机" prop="mobile" show-overflow-tooltip />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="SystemTenantForm" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as TenantApi from '@/api/system/tenant'
import { CommonStatusEnum } from '@/utils/constants'
import * as TenantPackageApi from '@/api/system/tenantPackage'
import * as ModuleApi from '@/api/system/module'

const defaultImgUrl = 'https://fileimage.hxhh.tech/hxhh-crm/huihai_logo.jpg' //默认logo地址，当用户没有配置自动添加

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  packageId: undefined,
  contactName: undefined,
  contactMobile: undefined,
  accountCount: undefined,
  expireTime: undefined,
  domain: undefined,
  showNonBizMenu: false,
  csPlatformId: undefined,
  status: CommonStatusEnum.ENABLE,
  tenantAdminList: undefined,
  imgUrl: undefined,
  csAccount: undefined,
  csPassword: undefined,
  csZkPlatformId: undefined,
  moduleIds: undefined,
  showExtraModule: true
})
const originModuleList = ref([])
const moduleList = computed(() => {
  if (!originModuleList.value) {
    return originModuleList.value
  }
  let newModuleList = originModuleList.value
  newModuleList.map((item) => {
    if (item.code === 'zk') {
      if (formData.value.csZkPlatformId) {
        item.disabled = false
      } else {
        item.disabled = true
      }
    }
    if (item.code === 'tc' || item.code === 'sight') {
      if (formData.value.csPlatformId) {
        item.disabled = false
      } else {
        item.disabled = true
      }
    }
  })
  return newModuleList
})

const csZkPlatform = ref([])
const csPlatform = ref([])

/**
 * 校验手机号
 */
// const validatePhone = (value, callback) => {
//   const regExp = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
//   if (!regExp.test(value)) {
//     callback(new Error('请输入正确的手机号'))
//   } else {
//     callback()
//   }
// }

const formRules = reactive({
  name: [{ required: true, message: '租户名不能为空', trigger: 'blur' }],
  packageId: [{ required: true, message: '租户套餐不能为空', trigger: 'blur' }],
  contactMobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  contactName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '租户状态不能为空', trigger: 'blur' }],
  accountCount: [{ required: true, message: '账号额度不能为空', trigger: 'blur' }],
  expireTime: [{ required: true, message: '过期时间不能为空', trigger: 'blur' }],
  // domain: [{ required: true, message: '绑定域名不能为空', trigger: 'blur' }],
  // imgUrl: [{ required: true, message: '图片路径不能为空', trigger: 'blur' }],
  username: [{ required: true, message: '用户账号不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const packageList = ref([]) // 租户套餐

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TenantApi.getTenant(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载套餐列表
  packageList.value = await TenantPackageApi.getTenantPackageList()
  // 获得模块列表
  originModuleList.value = await ModuleApi.getModuleList([])
  // 获得平台列表
  listPlatform()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log('============>', formData.value)
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (!formData.value.imgUrl) {
      formData.value.imgUrl = defaultImgUrl as any
    }
    const data = formData.value as unknown as TenantApi.TenantVO
    if (formType.value === 'create') {
      await TenantApi.createTenant(data)
      message.success(t('common.createSuccess'))
    } else {
      await TenantApi.updateTenant(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    packageId: undefined,
    contactName: undefined,
    contactMobile: undefined,
    accountCount: undefined,
    expireTime: undefined,
    domain: undefined,
    csPlatformId: undefined,
    status: CommonStatusEnum.ENABLE,
    csAccount: undefined,
    csPassword: undefined,
    csZkPlatformId: undefined,
    moduleIds: undefined,
    showExtraModule: true,
    showNonBizMenu: false
  }
  formRef.value?.resetFields()
  csZkPlatform.value = []
  csPlatform.value = []
}
const listPlatform = async () => {
  if (!formData.value.csAccount || !formData.value.csPassword) return // 密码和账号为空结束

  // 中考平台
  csZkPlatform.value = await TenantApi.getPlatform({
    username: formData.value.csAccount,
    password: formData.value.csPassword,
    systemFlag: 1
  })
  // 体测平台
  csPlatform.value = await TenantApi.getPlatform({
    username: formData.value.csAccount,
    password: formData.value.csPassword,
    systemFlag: 2
  })
}
</script>
